import { createRouter, createWebHistory } from 'vue-router'

import index from './components/index'
import login from "@/components/login/login";
import register from "@/components/login/register";

import home from "@/components/home";

// 创建路由实例对象
const router = createRouter({
    history: createWebHistory(),
    routes: [
        { path: '/', name:'index',component:index },
        { path: '/login', name:'login',component:login },
        { path: '/register', name:'register',component:register },
        { path: '/home', name:'home',component:home },
    ],
})

// 全局路由导航守卫
router.beforeEach((to, from, next) => {
    // 判断用户访问的是否为登录页
    if (to.path === '/login' || to.path==='/register') {
        return next()
    }

    // 获取 token 值
    const sessionToken = sessionStorage.getItem('token')
    const localToken = localStorage.getItem('token')

    if (sessionToken || localToken) {
        next()
    } else {
        next('/login')
    }
})

export default router
